/*
 * @Author: wuqingchun
 * @Date: 2024-03-29 10:52:33
 * @Description: 内存分配器实现
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-03-30 15:23:15
 */
#ifndef __MEM_ALLOCATOR_H__
#define __MEM_ALLOCATOR_H__

#include <stdlib.h>
#include <vector>
#include <array>
#include <list>
#include <unordered_map>
#include <atomic>

class MemAllocator
{
public:
    static const uint32_t MEM_SIZE_LEVEL = 24;
    static const uint32_t MEM_ALLOC_MAX_SIZE = (8 << MEM_SIZE_LEVEL);

private:
    /* data */

    struct MemNode
    {
        void *pPtr;
        size_t ulSize;
        uint32_t uiBlockID;
    };
    
    struct MemBlockItem
    {
        void* pPtr;
        size_t ulSize;
        uint32_t uiRefCount;

    };
    std::vector<struct MemBlockItem> m_vecMemPool;

    std::array<std::list<MemNode>, MEM_SIZE_LEVEL + 1> m_arrFreeList;
    std::unordered_map<void*, MemNode> m_mapUsedMem;                   // 已使用内存
    std::unordered_map<size_t, uint32_t> m_mapIndex;             
public:
    MemAllocator(/* args */);
    ~MemAllocator();

    void *Alloc(size_t ulSize);
    void Free(void *pPtr);

    void ShowMemInfo();
private:
    void * __AllocMemNode(MemNode& refNode, size_t ulAllocSize);
    uint32_t __Size2Index(size_t ulSize);
};

#endif //__MEM_ALLOCATOR_H__